package com.xm.controller;

import cn.hutool.db.sql.Order;
import com.xm.pojo.*;
import com.xm.service.orderService;
import com.xm.service.userService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.Array;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/Orders")
@CrossOrigin
public class orderController {

    @Autowired
    private orderService orderService;

    @Autowired
    private userService userService;


    /*
    * 列表1展示
    * */
    @GetMapping("/orderAll/{userId}")
    public R orderInfoAll(@PathVariable int userId){
        List<order> list= orderService.orderInfoAll(userId);
        if(list.size()>0){
            return R.OK().errorMsg("订单展示成功!").data("orderList",list);
        }else{
            return R.ERROR().errorMsg("暂无订单!");
        }
    }

    /*根据分类展示订单*/
    @GetMapping("/orderInfo/{userId}/{status}")
    public R orderInfoAll(@PathVariable int userId,@PathVariable int status){
        List<order> list= orderService.orderInfo(userId,status);
        if(list.size()>0){
            return R.OK().errorMsg("订单展示成功!").data("orderList",list);
        }else{
            return R.ERROR().errorMsg("暂无订单!");
        }
    }

    /*订单详情*/
    @GetMapping("/order/{orderNum}")
    public R orderInfoAll(@PathVariable String orderNum){
        List<order> list= orderService.order(orderNum);
        if(list.size()>0){
            return R.OK().errorMsg("订单展示成功!").data("orderList",list);
        }else{
            return R.ERROR().errorMsg("暂无订单!");
        }
    }



    /*未付款*/
    @GetMapping("/paymentFlag/{userId}")
    public R paymentFlag(@PathVariable int userId){
        List<order> list= orderService.paymentFlag(userId);
        if(list.size()>0){
            return R.OK().errorMsg("待支付订单展示成功!").data("orderList",list);
        }else{
            return R.ERROR().errorMsg("暂无待支付订单!");
        }
    }

    /*删除订单（未支付）*/
    @DeleteMapping("/deleteOrderFalse/{orderNum}")
    public R delorderFalse(@PathVariable String orderNum){
        boolean flag=orderService.delOrderFalse(orderNum);
        if(flag){
            return R.OK().errorMsg("已删除订单");
        }else{
            return R.ERROR().errorMsg("订单删除失败");
        }
    }
    /*删除订单（已完成）*/
    @DeleteMapping("/delorderTrue/{orderNum}")
    public R delorderTrue(@PathVariable String orderNum){
        boolean flag=orderService.delOrderTrue(orderNum);
        if(flag){
            return R.OK().errorMsg("已删除订单");
        }else{
            return R.ERROR().errorMsg("订单删除失败");
        }
    }

    /*支付*/
    @PutMapping("/updataOrder")
    public R updateOrder(@RequestBody String[] orderNum){
        boolean flags=true;
        User user = null;
       for(int i=0;i<orderNum.length;i++){
           //通过订单号查询订单信息
           List<order> list=orderService.order(orderNum[i]);
           /*获取用户信息*/
           user=userService.userInfoId(list.get(0).getUserId());
           double amount=userService.remainder(user.getUserName());
           if(amount>=list.get(0).getPrice()){//判断余额是否大于等于商品价格
               //大于商品价格
               boolean zhifu=userService.insertAccount(user.getUserName(),-(list.get(0).getPrice()),"商城消费");//添加消费信息
               if(zhifu){
                   boolean flag=orderService.updateOrder(1,orderNum[i]);//修改支付状态
                   order order=new order();
                   order.setOrderNum(orderNum[i]);
                   order.setStatus(1);
                   order.setUserId(list.get(0).getUserId());
                   boolean hisFlag=orderService.addHistory(order);//添加历史订单
                   orderService.updateStatus(1,orderNum[i]);//修改订单状态
                   if(!(flag && hisFlag)){
                       flags=false;
                       continue;
                   }
               }else{
                   flags=false;
                   continue;
               }
           }else{
               return R.ERROR().errorMsg("钱包余额不足！");
           }
       }
       if(flags){
           user.setAccount(new account(userService.remainder(user.getUserName()),userService.recharge(user.getUserName()),userService.consume(user.getUserName())));//支付成功，重新给钱包赋值
           return R.OK().errorMsg("支付成功！").data("user",user);
       }else{
           return R.ERROR().errorMsg("支付失败！");
       }
    }
    /*修改订单状态*/
    @PutMapping("/updataOrderStatus/{status}/{orderNum}")
    public R updateOrderStatus(@PathVariable int status,@PathVariable String orderNum){
        if(status!=5) {//判断用户是否是退款
            //不是，正常修改状态
            boolean flag = orderService.updateStatus(status, orderNum);
            if (flag) {
                return R.OK().errorMsg("订单状态修改成功！");
            } else {
                return R.ERROR().errorMsg("订单状态修改失败！");
            }
        }else{
            //退款，修改状态后将钱退回余额
            boolean flag = orderService.updateStatus(status, orderNum);
            if(flag){//判断状态是否修改
                //状态修改成功,进行退款
                List<order> list=orderService.order(orderNum);
                User users=userService.userInfoId(list.get(0).getUserId());
                boolean flags=userService.insertAccount(users.getUserName(),list.get(0).getPrice(),"退款");
                if(flags){
                    if (flag) {
                        User user=userService.userInfoId(list.get(0).getUserId());
                        user.setAccount(new account(userService.remainder(user.getUserName()),userService.recharge(user.getUserName()),userService.consume(user.getUserName())));
                        return R.OK().errorMsg("退款成功！").data("user",user);
                    } else {
                        return R.ERROR().errorMsg("退款失败！");
                    }
                }else{
                    return R.ERROR().errorMsg("退款失败！");
                }
            }else{
                return R.ERROR().errorMsg("退款失败！");
            }
        }
    }
    /*修改订单收货信息
    * order(
    * orderNum  订单号
    * contactName 收货人
    * contactMobile  手机号
    * contactAddress 收货地址
    * )
    * */
    @PutMapping("/updataOrderUser")
    public R updataOrderUser(@RequestBody order order){
        boolean flag=orderService.updateOrderUser(order);
        if(flag){
            return R.OK().errorMsg("收货信息修改成功！");
        }else{
            return R.ERROR().errorMsg("收货信息修改失败！");
        }
    }


    /*通过购物车到支付页*/
    @PostMapping("/carIdInfo")
    public R carIdInfo(@RequestBody int[] ids){
        List<order> order=orderService.carIdInfo(ids);
        return R.OK().data("order",order);
    }


    //生成订单/*
    //price        总价格
    //paymentFlag  付款状态
    //userId       用户id
    //contactName  收货人
    //contactMobile  收货电话
    //contactAddress 收货地址
    //message        订单备注
    //productId      商品id
    //quantity       购买数量
    //skuId          选项Id
    // */
    @PostMapping("/createOrder")
    public R createOrder(@RequestBody List<order> list){
        Map map=new HashMap();
        Date date=new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssds");
        String orderNum = sdf.format(date);//生成订单号
        boolean createFlag=true;
        for(int i=0;i<list.size();i++){
            order order=list.get(i);
            list.get(i).setOrderNum("O"+orderNum+i);//订单号
            boolean infoFlag=orderService.addInfo(list.get(i));
            double price=list.get(i).getPrice()/list.get(i).getQuantity();
            order.setPrice(price);
            order.setId("I"+orderNum+i);
            order.setOrderNum("O"+orderNum+i);
            boolean itemFlag=orderService.addItem(order);
            map.put(""+i,order);
            if(!(infoFlag && itemFlag)){
                createFlag=false;
            }
        }
        if(createFlag){
            return R.OK().data(map).errorMsg("已生成订单");
        }else{
            return R.ERROR().errorMsg("生成订单失败!");
        }
    }
}
